<template>
  <div style="height: 100%">
    <div class="mian-div">
      <ul style="margin: 0 10px; display: flex;align-content: center; width: 100%">
        <li style="flex: 1; display: flex; align-items: center;">
          <ul style="display: flex">
<!--            <li>想法</li>-->
            <li @click="addPan"><i class="iconfont el-icon-plus" title="新增"></i></li>
          </ul>
        </li>
        <li style="flex: 0;">
          <ul style="display: flex">
            <li><el-button @click="getNeedList">刷新</el-button></li>
            <li><el-button @click="goModeling">去建模</el-button></li>
            <li><el-button @click="goBack">返回</el-button></li>
          </ul>
        </li>
      </ul>
    </div>
    <div style="margin-top: 20px" ref="need_div">
      <need-list-item :moveXYFun="moveXYFun" v-for="(item, index) in positionData" :key="index"
                      :soruceData="item" @delLane="delLane"
                      :itemPosition="{index: index, total: positionData.length}"></need-list-item>
    </div>
    <need-line-dialog :visible.sync="needLineDialogvisible" :formData="needLineDialogformData" @createSuc="createSuc"></need-line-dialog>
  </div>
</template>

<script>
import needListItem from "./needListItem";
import projectNeedApi from "@/api/organizationApi/projectNeedApi";
import projectNeedSwimlane from "@/api/organizationApi/projectNeedSwimlane";
import needLineDialog from "./needLineDialog";

export default {
  name: 'needList',
  provide () {
    return {
      initData: this
    }
  },
  components: {
    needListItem,
    needLineDialog
  },
  data () {
    return {
      needLineDialogformData: {},
      needLineDialogvisible: false,
      itemindex: 0,
      Projectid: this.$route.params.id,
      // 位置信息
      positionData: []
    }
  },
  mounted() {
    this.getNeedList()
  },
  methods: {
    // 返回上一页
    goBack () {
      this.$router.push(`/view/project/details/${this.Projectid}`)
    },
    // 去建模
    goModeling () {
      this.$router.push(`/view/project/modelMain/${this.Projectid}`)
    },
    // 删除泳道
    delLane (itemPosition) {
      let a = this.positionData[itemPosition.index].id
      projectNeedSwimlane.delSwimById({id: a}).then(res => {
        if (res) this.$message({type: res.code === 1 ? 'success' : 'error', message: res.message})
        if (res.code === 1) {
          this.getNeedList()
        }
      })
    },
    // 保存
    save () {
      // console.log(this.positionData);
    },
    saveSwimlane () {
      let c = []
      this.positionData.forEach(it => {
        if (it.id.toString().length < 10) {
          c.push({
            Projectid: this.Projectid,
            Type: 1,
            Ycoordinate: it.contentHeight
          })
        }
      })
      projectNeedSwimlane.create(c).then(res => {
        // console.log(res)
      })
    },
    saveNeeds () {

    },
    // 泳道创建成功
    createSuc (swimlane) {
      this.positionData.push({
        id: swimlane.Id,
        Name: swimlane.Name,
        contentHeight: swimlane.Ycoordinate,
        child: []
      })
    },
    addPan () {
      this.needLineDialogformData.Projectid = this.Projectid
      this.needLineDialogvisible = true
    },
    // 获取需求数据
    getNeedList () {
      let query1 = Object.assign({id: this.Projectid})
      let query = JSON.parse(JSON.stringify(query1))
      projectNeedSwimlane.getList(query).then(res1 => {
        projectNeedApi.getPage(query).then(res => {
          if (res.Needs) {
            this.initValueFun(res.Needs, res1)
          }
        }).catch((err) => {
          this.$message.error('获取需求列表失败')
          console.log(err)
        });
      })
    },
    // 初始化值
    initValueFun (needs, sw) {
      this.positionData = []
      sw.forEach(it2 => {
        let w = []
        let Ycoordinate = ''
        needs.forEach(it => {
          if (it.Crosswise === it2.Id) {
            w.push(Object.assign(it, {
              x: it.Xcoordinate,
              y: it.Ycoordinate,
              localHeight: it.High || '100',
              localWidth: it.Width || '100',
            }))
            Ycoordinate = it2.Ycoordinate
          }
        })
        this.positionData.push({
          id: it2.Id,
          Name: it2.Name,
          contentHeight: Ycoordinate,
          Planid: it2.Planid,
          child: w
        })
      })
    },
    // 交换行数据
    exchangeData (w) {
      let { contentHeight, localHeight, y, id } = w.item
      localHeight = Number(localHeight.toString().replace('px', ''))
      localHeight = localHeight + w.item.paddingtb
      contentHeight = Number(contentHeight.toString().replace('px', ''))
      let i = w.itemPosition.index
      if ((w.itemPosition.index + 1) !== w.itemPosition.total) {
        i += 1
      }
      let headHeight = this.positionData[i].headHeight
      // 下拉但是没有拉到下一个有效值时，会处于底部
      if (y < (contentHeight + headHeight) && y > (contentHeight - localHeight)) {
        w.y = Number(contentHeight) - Number(localHeight)
        y = w.y
      }
      // 上下移动
      if (y < 0 && (y + localHeight > 0)) {
        w.y = 0
        y = w.y
      }
      if (y > (contentHeight + headHeight) || y < 0) {
        let pindex = this.exchangeIndex(y, w.itemPosition.index)
        if (pindex.index !== w.itemPosition.index && pindex.index >= 0) {
          let iidx = this.positionData[w.itemPosition.index].child.indexOf(w.item)
          if (iidx >= 0) {
            this.positionData[w.itemPosition.index].child.splice(iidx, 1)
            // w.item.y = pindex.yl
            w.y = pindex.yl
            if (w.y > contentHeight - localHeight) {
              w.y = Number(contentHeight) - Number(localHeight)
            }
            y = w.y
            w.item.Crosswise = this.positionData[pindex.index].id
            this.positionData[pindex.index].child.push(w.item)
          }
        }
        if (pindex.index === -1) {
          if (y > 0) {
            w.y = Number(contentHeight) - Number(localHeight)
          } else {
            w.y = 0
          }
        }
      }
      // console.log(w)
      this.saveMoveUpFun(w)
      return w
    },
    saveMoveUpFun (item) {
      let b = JSON.parse(JSON.stringify(item))
      let a = JSON.parse(JSON.stringify(item.item))
      a.Xcoordinate = Number(b.x)
      a.Ycoordinate = Number(b.y)
      a.High = Number((a.localHeight || '').toString().replace('px', ''))
      a.Width = Number((a.localWidth || '').toString().replace('px', ''))
      projectNeedApi.update(a).then(res => {
        // console.log(res)
      })
    },
    exchangeIndex (y, index) {
      let a = -1
      let yl = -1
      // 往下移动
      if (y > 0) {
        let a = this.positionData.some((it, inx) => {
          if (index <= inx) {
            let hh = 0
            if (this.positionData.length !== (inx + 1)) hh = this.positionData[inx + 1].headHeight.toString().replace('px', '')
            y -= (Number(it.contentHeight.toString().replace('px', '')) + Number(hh))
            if (y <= 0) {
              index = inx
              return true
            }
            yl = y
          }
        })
        if (!a) index = -1 // 高度超过总高度
      } else {
        // 往上移动
        let a = this.positionData.slice(0, this.positionData.length).reverse()
        a = a.some((it, inx) => {
          if (inx >= this.positionData.length - index - 1) {
            let ch = 0
            if (inx + 1 <= a.length && (inx !== this.positionData.length - index - 1)) ch = it.contentHeight.toString().replace('px', '')
            y += (Number(it.headHeight.toString().replace('px', '')) + Number(ch))
            yl = y
            if (y >= 0) {
              index = this.positionData.length - inx - 1
              return true
            }
          }
        })
        if (!a) index = -1 // 高度超过总高度
      }
      return {
        yl,
        index
      }
    },
    moveXYFun (x, y, hh, h) {
      // console.log(this.$refs['need_div'].clientHeight)
      // console.log(x, y, hh, h)
      return {
        x,y
      }
    },
    itemClick (index) {
      this.itemindex = index
      // console.log(this.itemindex)
    }
  }
}
</script>

<style scoped lang="scss">
.mian-div{
  height: 40px;
  width: 100%;
  box-shadow: 0 0 20px 5px #cccccc;
  display: flex;
  align-items: center;
  & li {
    cursor: pointer;
  }
  & li+li {
    margin-left: 10px;
  }
}
ul li {
  list-style: none;
}
</style>
